package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.constant.UserConstants;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.constant.RedisConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.BitFieldSubCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 发送短信验证码
     * @param phone
     * @return
     */
    @Override
    public void sendCode(String phone) {
        String code = RandomUtil.randomString(6);
        stringRedisTemplate.opsForValue().set(RedisConstants.LOGIN_CODE_KEY+phone,code);
        stringRedisTemplate.expire(RedisConstants.LOGIN_CODE_KEY+phone,RedisConstants.LOGIN_CODE_TTL, TimeUnit.MINUTES);
        log.info("验证码发送：{}",code);
    }

    /**
     * 登录功能
     * @param loginForm
     */
    @Transactional
    @Override
    public String login(LoginFormDTO loginForm) {
        String code = stringRedisTemplate.opsForValue().get(RedisConstants.LOGIN_CODE_KEY+loginForm.getPhone());
        //校验成功
        User user = query().eq("phone", loginForm.getPhone()).one();
        //不存在则注册
        if(user == null){
            user = new User();
            user.setPhone(loginForm.getPhone());
            user.setPassword(UserConstants.DEFAULT_PASSWORD);
            user.setIcon(UserConstants.DEFAULT_ICON);
            user.setNickName(UserConstants.NICKNAME_PREFIX+UUID.randomUUID().toString().substring(0,8));
            save(user);
        }

        //存入Redis
        UserDTO userDTO = new UserDTO();
        BeanUtil.copyProperties(user,userDTO);
        log.debug("user:{}",user);
        log.debug("userDTO:{}",userDTO);
        Map<String, Object> map = BeanUtil.beanToMap(userDTO);
        log.debug("map:{}",map);
        map.put("id",String.valueOf(user.getId()));
        String token = UUID.randomUUID().toString();
        log.debug("初始token:{}",token);
        stringRedisTemplate.opsForHash().putAll(RedisConstants.LOGIN_USER_KEY+token,map);
        return token;
    }

    /**
     * 签到
     */
    @Override
    public void sign() {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //获取今天所属年月
        LocalDateTime now = LocalDateTime.now();
        String month = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //存入redis
        stringRedisTemplate.opsForValue().setBit(RedisConstants.USER_SIGN_KEY+userId+month,dayOfMonth-1,true);
    }

    /**
     * 统计连续签到天数
     * @return
     */
    @Override
    public Integer signCount() {
        //获取用户
        Long userId = UserHolder.getUser().getId();
        //获取今天所属年月
        LocalDateTime now = LocalDateTime.now();
        String month = now.format(DateTimeFormatter.ofPattern(":yyyyMM"));
        //获取今天是本月第几天
        int dayOfMonth = now.getDayOfMonth();
        //获取签到表
        List<Long> results = stringRedisTemplate.opsForValue().bitField(RedisConstants.USER_SIGN_KEY + userId + month,
                BitFieldSubCommands
                        .create()
                        .get(BitFieldSubCommands.BitFieldType.unsigned(dayOfMonth)).valueAt(0));
        if(results.size()==0||results==null){
            return 0;
        }
        Long result = results.get(0);
        if(result==0){
            return 0;
        }
        Integer count = 0;
        while(true){
            long isSign = result & 1;
            if(isSign == 1){
                result >>>= 1;
                count ++;
            }else {
                break;
            }
        }
return count;
    }
}
